package com.wobangkj.common.api.log;

import com.wobangkj.tool.api.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;

/**
 * 日志记录
 *
 * @author lu
 */

@Controller
@RequestMapping(value = "/log")
@Slf4j
public class LogController {

	// 文件写入路径
	private static final String AppletLog = "/common-service/log/front.log";
//	private static final String AppletLog = "/log/front.log";

	/**
	 * 记录错误日志
	 *
	 * @param error
	 * @return
	 */
	@PostMapping("/error")
	@ResponseBody
	public Object upload(@RequestBody String error) {
		log.error(error);
		return Result.GetMapData(Result.CodeSuccess, Result.MsgSuccess);
	}

	@PostMapping("/front")
	@ResponseBody
	public Object front(@RequestBody String msg) {
		//获取根目录
		File rootFile = null;
		// 写入文件
		RandomAccessFile randomFile = null;
		try {
			rootFile = new File("");
			File appletLog = new File(rootFile.getAbsolutePath() + AppletLog);
			// 文件不存在则创建
			if (!appletLog.exists()) {
				appletLog.createNewFile();
				// 写入文件
				randomFile = new RandomAccessFile(appletLog.getAbsolutePath(), "rw");
				randomFile.writeBytes("[\n]");
				randomFile.close();
			}
			// 写入文件
			randomFile = new RandomAccessFile(appletLog.getAbsolutePath(), "rw");
			randomFile.seek(randomFile.length() - 1);
			//log.info("长度" + randomFile.length());
			if (randomFile.length() == 3) {
				randomFile.write(msg.getBytes(StandardCharsets.UTF_8));
				randomFile.writeBytes("\n");
			} else {
				randomFile.writeBytes(",");
				randomFile.write(msg.getBytes(StandardCharsets.UTF_8));
				randomFile.writeBytes("\n");
			}
			randomFile.writeBytes("]");
			randomFile.close();
		} catch (Exception e) {
			log.error("[小程序日志记录错误]" + e.getMessage());
		}

		return Result.GetMapData(Result.CodeSuccess, Result.MsgSuccess);
	}

}
